java使用递归和二叉树计算算术表达式
我在做一个递归算法时遇到了一些问题,它能够做一些基本的运算,包括乘法、除法、减法、加法和幂。我正在使所有的东西都工作,除了我开始加入括号的时候。我知道他们优先,但我不知道怎么做
代码背后的基本思想是创建一个二叉树,其中每个节点都是一个操作符,从树的顶部开始,优先级最低,从树的底部开始。我的方法是首先检测是否有右括号,检查右括号上是否有运算符,如果有有效运算符,树的左侧部分将是右括号之前的所有内容,右侧部分将是运算符之后的所有内容。我面临的问题是何时考虑开头括号…
这是我的密码:
public static float eval(String exp) {
System.out.println(" \nNEW CALL STACK : " + exp);
float res = 0;
// if it starts with a negative
if(exp.startsWith("-")) {
return -1 * eval(exp.substring(1));
}
int opIndex = -1;
// start with closing paren
if (opIndex == -1) {
for (int i = exp.length() - 1; i >= 0; i--) {
if (exp.charAt(i) == ')') {
opIndex = i;
break;
}
}
}
if (opIndex == -1) {
for (int i = exp.length() - 1; i >= 0; i--) {
if (exp.charAt(i) == '+' || exp.charAt(i) == '-') {
opIndex = i;
break;
}
}
}
if (opIndex == -1) {
for (int i = exp.length() - 1; i >= 0; i--) {
if (exp.charAt(i) == '*' || exp.charAt(i) == '/') {
opIndex = i;
break;
}
}
}
if (opIndex == -1) {
for (int i = exp.length() - 1; i >= 0; i--) {
if (exp.charAt(i) == '^') {
opIndex = i;
break;
}
}
}
if (opIndex != -1) {
char operator = exp.charAt(opIndex);
String left = "";
String right = "";
// check to see if there's anything after the closing paren
if( operator == ')' && !exp.substring(opIndex+1, opIndex + 2).equals("")) {
left = exp.substring(0, opIndex);
operator = exp.charAt(opIndex+1);
right = exp.substring(opIndex+2);
} else {
left = exp.substring(0, opIndex); // left sub-tree
right= exp.substring(opIndex + 1, exp.length()); // right sub-tree
}
// operator is the "node"
System.out.println("Left: " + left + " operator: " + operator + " Right:" + right);
// start traversing
if (operator == '+') {
res = eval(left) + eval(right);
} else if (operator == '-') {
res = eval(left) - eval(right);
} else if (operator == '/') {
res = eval(left) / eval(right);
} else if( operator == '^') {
res = getPower( new Float (left), new Float( right) );
} else if( operator == '*') {
res = eval(left) * eval(right);
}
} else {
if(isNumber(exp)) return new Float(exp);
return 0;
}
return res;
}
任何提示或建议都将不胜感激
编辑
我不是在寻找内置Java库来实现这一点。我只是想弄清楚我错过了什么,我错在哪里
共 (0) 个答案